<template>
  <t-dialog
    v-model:visible="dialogVisible"
    :header="formMode === 'create' ? '新增用户' : '编辑用户'"
    width="600px"
    :confirm-btn="null"
    :cancel-btn="null"
    @close="handleClose"
  >
    <t-form
      ref="formRef"
      :data="formData"
      :rules="formRules"
      label-width="80px"
      @submit="handleSubmit"
    >
      <t-form-item label="用户名" name="username">
        <t-input 
          v-model="formData.username" 
          placeholder="请输入用户名"
          :disabled="formMode === 'edit'"
        />
      </t-form-item>
      
      <t-form-item label="昵称" name="nickname">
        <t-input v-model="formData.nickname" placeholder="请输入昵称" />
      </t-form-item>
      
      <t-form-item label="邮箱" name="email">
        <t-input v-model="formData.email" placeholder="请输入邮箱" />
      </t-form-item>
      
      <t-form-item label="手机号" name="phone">
        <t-input v-model="formData.phone" placeholder="请输入手机号" />
      </t-form-item>
      
      <t-form-item v-if="formMode === 'create'" label="密码" name="password">
        <t-input 
          v-model="formData.password" 
          type="password" 
          placeholder="请输入密码"
        />
      </t-form-item>
      
      <t-form-item label="状态" name="status">
        <t-radio-group v-model="formData.status">
          <t-radio :value="1">正常</t-radio>
          <t-radio :value="0">禁用</t-radio>
        </t-radio-group>
      </t-form-item>
      
      <t-form-item label="角色" name="roleIds">
        <t-select 
          v-model="formData.roleIds" 
          placeholder="请选择角色"
          multiple
          clearable
        >
          <t-option 
            v-for="role in roleList" 
            :key="role.id" 
            :value="role.id" 
            :label="role.name" 
          />
        </t-select>
      </t-form-item>
      
      <t-form-item label="头像" name="avatar">
        <t-upload
          v-model="formData.avatar"
          theme="image"
          accept="image/*"
          :max="1"
          :size-limit="{ size: 2, unit: 'MB' }"
          tips="支持上传 jpg、png 格式图片，文件大小不超过 2MB"
        />
      </t-form-item>
    </t-form>
    
    <template #footer>
      <t-space>
        <t-button theme="default" @click="handleClose">取消</t-button>
        <t-button theme="primary" :loading="submitting" @click="handleSubmit">
          {{ formMode === 'create' ? '创建' : '更新' }}
        </t-button>
      </t-space>
    </template>
  </t-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useUserManagementStore } from '@/stores/userManagement'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    default: 'create', // 'create' | 'edit'
    validator: (value) => ['create', 'edit'].includes(value)
  },
  userData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success'])

const userManagementStore = useUserManagementStore()
const formRef = ref()
const submitting = ref(false)

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单数据
const formData = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  password: '',
  status: 1,
  roleIds: [],
  avatar: []
})

// 角色列表
const roleList = ref([])

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', type: 'error' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', type: 'error' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', type: 'error' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', type: 'error' },
    { max: 50, message: '昵称长度不能超过50个字符', type: 'error' }
  ],
  email: [
    { required: true, message: '请输入邮箱', type: 'error' },
    { email: true, message: '请输入正确的邮箱格式', type: 'error' }
  ],
  phone: [
    { required: true, message: '请输入手机号', type: 'error' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', type: 'error' }
  ],
  password: [
    { required: true, message: '请输入密码', type: 'error' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', type: 'error' }
  ],
  roleIds: [
    { required: true, message: '请选择角色', type: 'error' }
  ]
}

// 监听用户数据变化
watch(() => props.userData, (newData) => {
  if (newData && props.mode === 'edit') {
    Object.assign(formData, {
      username: newData.username || '',
      nickname: newData.nickname || '',
      email: newData.email || '',
      phone: newData.phone || '',
      password: '', // 编辑时不显示密码
      status: newData.status ?? 1,
      roleIds: newData.roleIds || [],
      avatar: newData.avatar ? [{ url: newData.avatar }] : []
    })
  }
}, { immediate: true })

// 监听对话框显示状态
watch(() => props.visible, (visible) => {
  if (visible) {
    loadRoleList()
    if (props.mode === 'create') {
      resetForm()
    }
  }
})

// 加载角色列表
const loadRoleList = async () => {
  const result = await userManagementStore.getRoleList()
  if (result.success) {
    roleList.value = result.data
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    username: '',
    nickname: '',
    email: '',
    phone: '',
    password: '',
    status: 1,
    roleIds: [],
    avatar: []
  })
  formRef.value?.clearValidate()
}

// 处理提交
const handleSubmit = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  submitting.value = true
  try {
    const submitData = {
      ...formData,
      avatar: formData.avatar?.[0]?.url || '',
      roles: roleList.value.filter(role => formData.roleIds.includes(role.id))
    }

    let result
    if (props.mode === 'create') {
      result = await userManagementStore.createUser(submitData)
    } else {
      result = await userManagementStore.updateUser(props.userData.id, submitData)
    }

    if (result.success) {
      MessagePlugin.success(result.message)
      emit('success')
      handleClose()
    } else {
      MessagePlugin.error(result.message)
    }
  } catch (error) {
    MessagePlugin.error('操作失败')
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}
</script>

<style scoped>
:deep(.t-form-item__label) {
  font-weight: 500;
}

:deep(.t-upload__dragger) {
  height: 120px;
}
</style>
